/**
 * 固定资产管理系统 - 现代化Admin交互脚本 5.0
 * 作者：资产管理团队
 * 版本：v5.0.0
 * 描述：提供现代化的用户交互体验
 */

(function() {
    'use strict';

    // 确保页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        console.log('🚀 固定资产管理系统 v5.0 已启动');
        
        // 初始化所有功能
        initializeTheme();
        initializeAnimations();
        initializeTableEnhancements();
        initializeFormEnhancements();
        initializeNotifications();
        initializeKeyboardShortcuts();
        initializeBackToTop();
        
        // 避免任何自动刷新功能
        preventAutoRefresh();
    });

    /**
     * 主题初始化
     */
    function initializeTheme() {
        // 添加主题切换功能
        const header = document.querySelector('#header');
        if (header) {
            header.style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
        }

        // 为所有卡片添加现代化样式
        const cards = document.querySelectorAll('.module, .card');
        cards.forEach(card => {
            card.classList.add('animate-fade-in');
        });
    }

    /**
     * 动画效果初始化
     */
    function initializeAnimations() {
        // 为表格行添加悬停效果
        const tableRows = document.querySelectorAll('table tbody tr');
        const isSuppressedContext = () => {
            return (
                document.body.classList.contains('modal-open') ||
                !!document.querySelector('.modal.show') ||
                !!document.querySelector('#assetLogsContainer, .asset-logs, .related-logs, .asset-log, .asset-log-modal, .log-item')
            );
        };
        tableRows.forEach(row => {
            row.addEventListener('mouseenter', function() {
                if (isSuppressedContext()) return;
                this.style.backgroundColor = 'rgba(102, 126, 234, 0.05)';
                this.style.transform = 'scale(1.005)';
                this.style.willChange = 'transform, background-color';
            }, { passive: true });
            
            row.addEventListener('mouseleave', function() {
                this.style.backgroundColor = '';
                this.style.transform = 'scale(1)';
                this.style.willChange = '';
            }, { passive: true });
        });

        // 为按钮添加点击效果
        const buttons = document.querySelectorAll('.button, .btn, input[type="submit"]');
        buttons.forEach(button => {
            button.addEventListener('click', function(e) {
                // 创建波纹效果
                const ripple = document.createElement('span');
                ripple.classList.add('ripple');
                this.appendChild(ripple);
                
                setTimeout(() => {
                    ripple.remove();
                }, 600);
            });
        });
    }

    /**
     * 表格增强功能
     */
    function initializeTableEnhancements() {
        // 添加表格排序功能
        const headers = document.querySelectorAll('table thead th');
        headers.forEach(header => {
            if (header.textContent.trim()) {
                header.style.cursor = 'pointer';
                header.addEventListener('click', function() {
                    console.log('🔄 排序列:', this.textContent);
                    // 这里可以添加实际的排序逻辑
                });
            }
        });

        // 添加表格搜索过滤
        const searchInput = document.querySelector('#searchbar');
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                const rows = document.querySelectorAll('table tbody tr');
                
                rows.forEach(row => {
                    const text = row.textContent.toLowerCase();
                    row.style.display = text.includes(searchTerm) ? '' : 'none';
                });
            });
        }
    }

    /**
     * 表单增强功能
     */
    function initializeFormEnhancements() {
        // 为输入框添加焦点效果
        const inputs = document.querySelectorAll('input, textarea, select');
        inputs.forEach(input => {
            input.addEventListener('focus', function() {
                this.parentElement.classList.add('form-field-focused');
            });
            
            input.addEventListener('blur', function() {
                this.parentElement.classList.remove('form-field-focused');
            });
        });

        // 表单验证增强
        const forms = document.querySelectorAll('form');
        forms.forEach(form => {
            form.addEventListener('submit', function(e) {
                console.log('📝 表单提交中...');
                // 可以添加自定义验证逻辑
            });
        });
    }

    /**
     * 通知系统
     */
    function initializeNotifications() {
        // 美化现有的消息
        const messages = document.querySelectorAll('.messagelist li');
        messages.forEach(message => {
            message.style.borderRadius = '8px';
            message.style.padding = '1rem';
            message.style.marginBottom = '0.5rem';
            message.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)';
        });

        // 创建通知函数
        window.showNotification = function(message, type = 'info') {
            const notification = document.createElement('div');
            notification.className = `notification notification-${type}`;
            notification.textContent = message;
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 1rem 1.5rem;
                border-radius: 8px;
                background: linear-gradient(135deg, #4fd1c7 0%, #4299e1 100%);
                color: white;
                box-shadow: 0 4px 15px rgba(0,0,0,0.2);
                z-index: 9999;
                animation: slideInRight 0.3s ease-out;
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.style.animation = 'slideOutRight 0.3s ease-in';
                setTimeout(() => notification.remove(), 300);
            }, 3000);
        };
    }

    /**
     * 键盘快捷键
     */
    function initializeKeyboardShortcuts() {
        document.addEventListener('keydown', function(e) {
            // Ctrl + / 打开搜索
            if (e.ctrlKey && e.key === '/') {
                e.preventDefault();
                const searchInput = document.querySelector('#searchbar');
                if (searchInput) {
                    searchInput.focus();
                }
            }
            
            // ESC 清空搜索
            if (e.key === 'Escape') {
                const searchInput = document.querySelector('#searchbar');
                if (searchInput && searchInput === document.activeElement) {
                    searchInput.value = '';
                    searchInput.dispatchEvent(new Event('input'));
                }
            }
        });
    }

    /**
     * 返回顶部按钮
     */
    function initializeBackToTop() {
        // 创建返回顶部按钮
        const backToTop = document.createElement('button');
        backToTop.innerHTML = '⬆️';
        backToTop.className = 'back-to-top';
        backToTop.style.cssText = `
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            cursor: pointer;
            display: none;
            z-index: 1000;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            transition: all 0.3s ease;
            font-size: 20px;
        `;
        
        document.body.appendChild(backToTop);
        
        // 显示/隐藏逻辑
        window.addEventListener('scroll', function() {
            if (window.scrollY > 300) {
                backToTop.style.display = 'block';
            } else {
                backToTop.style.display = 'none';
            }
        });
        
        // 点击返回顶部
        backToTop.addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
    }

    /**
     * 防止自动刷新
     */
    function preventAutoRefresh() {
        // 清除所有可能的定时器
        const highestTimeoutId = setTimeout(function(){}, 1);
        for (let i = 0; i < highestTimeoutId; i++) {
            clearTimeout(i);
        }
        
        const highestIntervalId = setInterval(function(){}, 9999);
        for (let i = 0; i < highestIntervalId; i++) {
            clearInterval(i);
        }
        
        // 禁用自动刷新功能
        if (window.location && window.location.reload) {
            const originalReload = window.location.reload;
            window.location.reload = function() {
                console.log('🚫 自动刷新已被阻止');
                return false;
            };
        }
        
        console.log('✅ 自动刷新防护已启用');
    }

    /**
     * 工具函数：防抖
     */
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    /**
     * 工具函数：节流
     */
    function throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }

    // 添加CSS动画样式
    const style = document.createElement('style');
    style.textContent = `
        @keyframes slideInRight {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        
        @keyframes slideOutRight {
            from { transform: translateX(0); opacity: 1; }
            to { transform: translateX(100%); opacity: 0; }
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .animate-fade-in {
            animation: fadeIn 0.6s ease-out;
        }
        
        .form-field-focused {
            transform: scale(1.02);
            transition: all 0.3s ease;
        }
        
        .ripple {
            position: absolute;
            border-radius: 50%;
            background: rgba(255,255,255,0.6);
            transform: scale(0);
            animation: ripple 0.6s linear;
            pointer-events: none;
        }
        
        @keyframes ripple {
            to {
                transform: scale(4);
                opacity: 0;
            }
        }
        
        .back-to-top:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3) !important;
        }
    `;
    document.head.appendChild(style);

})();